package cn.uway.controller.demo;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import cn.uway.utils.WebUtils;

@Controller
@RequestMapping(value = "/file")
public class FileUploadController {
	
	private Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@RequestMapping(value = "toUpload")
	public String toUpload( HttpServletRequest request, HttpServletResponse response ) {
		return "testUploadFile";		
	}
	
	@RequestMapping(value = "upload")
	@ResponseBody
	public String upload(HttpServletRequest request, @RequestParam(value="file1",required=false) MultipartFile file1,
			      @RequestParam(value="file2",required=false) MultipartFile file2) {
		String data = request.getParameter("data");	
		String remark = request.getParameter("remark");	
		System.out.println("===============data="+data);
		System.out.println("===============remark="+remark);
		
		String uploadPath = "/home/upload";
		File folder = new File(uploadPath);
 		if(!folder.exists()){
 			folder.mkdirs();
 		}
		if(file1!=null && !file1.isEmpty()){
			System.out.println("============file1.size="+file1.getSize());
			//保存文件到服务器硬盘
			String filePath = saveFile( uploadPath, file1);
			
			System.out.println("===============filePath1="+filePath);
		}
		if(file2!=null && !file2.isEmpty()){
			System.out.println("============file2.size="+file2.getSize());
			//保存文件到服务器硬盘
			String filePath = saveFile( uploadPath, file2);
			
			System.out.println("===============filePath2="+filePath);
		}
		return "ok";		
	}
	
	/**
	 * 特别注意，使用MultipartFile[]数组的话，注解里面的values值要和form表单里file input的名字-name一致，并且file input的名字要全部相同，否则不能形成数组集合
	 * @param request
	 * @param files
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "upload2")
	@ResponseBody
	public String upload( HttpServletRequest request, @RequestParam(value = "files", required=false) MultipartFile[] files,
			 HttpServletResponse response ) throws Exception {		
		String data = request.getParameter("data");	
		String remark = request.getParameter("remark");	
		System.out.println("===============data="+data);
		System.out.println("===============remark="+remark);
		
		String uploadPath = "/home/upload";
		File folder = new File(uploadPath);
 		if(!folder.exists()){
 			folder.mkdirs();
 		}
		
 		for(MultipartFile file : files){
 			
 			if(file!=null && !file.isEmpty()){ 				
 				System.out.println("============file.size="+file.getSize());
 				//保存文件到服务器硬盘
 				String filePath = saveFile( uploadPath, file); 		 				
 				System.out.println("===============filePath="+filePath);
 			}
 		}	
 		
		return "ok";		
	}
	
	
	private  String  saveFile(String uploadPath, MultipartFile mf){
		String filePath = null;
		String fileName = mf.getOriginalFilename();			
		BufferedInputStream bis = null;
		OutputStream out = null;
		try {
			Integer index = fileName.lastIndexOf(".");
			String ext = fileName.substring(index + 1);
			String newFileName = WebUtils.createUUID() + "." + ext.toLowerCase();
			filePath = uploadPath+"/" + newFileName;
			bis = new BufferedInputStream(mf.getInputStream());
			out = new BufferedOutputStream( new FileOutputStream(filePath) );
			int bytesRead = 0;  
			byte[] buffer = new byte[8192];  
            while ( (bytesRead=bis.read(buffer)) !=-1 ) {  
                out.write(buffer, 0, bytesRead);  
            }  
            //刷新缓冲区  
            out.flush();  
		}catch (Exception e) {
			logger.error("写入文件出错", e);
			filePath = null;
		}
		finally{
			if(bis!=null){
				try {
					bis.close();
				} 
				catch (IOException e) {
					e.printStackTrace();
				}
			}
			if(out!=null){
				try {
					out.close();
				} 
				catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return filePath;
	}

}
